//
//  CYNormaladdVC.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/5/25.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYNormaladdVC.h"
#import "CYUser.h"
#import "CYHttpTool.h"
#import "CYLoginHttpTool.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "CYLifePhotoVC.h"
#import "MBProgressHUD+LE.h"
#import "UIButton+WebCache.h"
#import "CYCreditTool.h"
#import "UIImageView+WebCache.h"
#import "MWPhotoBrowser.h"
#import "LEPhotoBrowserTool.h"
#import "LEUnitView+LE.h"
#import "LEBarButtonItem.h"
#import "CustomIOSAlertView.h"


@interface CYNormaladdVC ()

@property(nonatomic,strong)UIView *bg;
@property(nonatomic,strong)UIView *weixinbg;
@property (weak, nonatomic) IBOutlet UILabel *addresspersonLab;
@property (weak, nonatomic) IBOutlet UILabel *qqLab;
@property (weak, nonatomic) IBOutlet UILabel *weixinLab;

@property (nonatomic, strong) NSString *weiXin;
@property (nonatomic, strong) NSString *qq;
@property (nonatomic, strong) NSArray *photoArray;
@property (nonatomic, strong) NSMutableArray *creditarray;
@property (nonatomic, strong) NSMutableArray *lphonesarray;
@property (nonatomic, strong) NSMutableArray *namearray;
@property (nonatomic, strong) NSMutableArray *submitArray;

@property (weak, nonatomic) IBOutlet UIButton *shilitu1;

@property (weak, nonatomic) IBOutlet UIButton *shilitu2;
@property (weak, nonatomic) IBOutlet UILabel *recordLab;
@property (weak, nonatomic) IBOutlet UIView *recordView;
@property (weak, nonatomic) IBOutlet UIView *submitView;

@property (nonatomic, strong) NSMutableArray *photoUrls;
@property (nonatomic, strong) NSMutableArray *shenghuorecordArray;

@property (nonatomic, strong) UILabel *titlelab;

@property (nonatomic, strong) UIView *weixinView;

@property (nonatomic, strong) NSString *imageUrl;
@property (nonatomic, strong) NSString *weixinname;


@end

@implementation CYNormaladdVC

- (void)viewDidLoad {
     [super viewDidLoad];
     _creditarray = [[NSMutableArray alloc]init];
     _lphonesarray = [[NSMutableArray alloc]init];
     _namearray = [[NSMutableArray alloc] init];
     _submitArray = [[NSMutableArray alloc]init];
     
     _photoUrls = [[NSMutableArray alloc]init];
     _shenghuorecordArray = [[NSMutableArray alloc]init];
     
     [_shilitu1 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/prove/shenghuozhao1.jpg"] forState:UIControlStateNormal];
     [_shilitu2 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/prove/shenghuozhao2.jpg"] forState:UIControlStateNormal];
     
     [self setupUploadView];
     [self setimagecerIDView];
     [self loaddetails];
     
     LEBarButtonItem *submit = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_done_white_24dp"] andSelImage:nil andTitle:@"提交" target:self action:@selector(submitclick)];
     self.navigationItem.rightBarButtonItem = submit;
    // Do any additional setup after loading the view from its nib.
}

-(void)submitclick{
     if (_photoUrls.count == 0) {
          CYAlertView(@"请最少提交一张图");
          return;
          
     }
     CYUser *user = [CYLoginHttpTool userData].user;
     NSString *userId = user.userId;
     NSString *token = user.token;
     for (int i=0; i<_photoUrls.count; i++) {
          NSDictionary *dic1 = @{@"generalPicAddress":_photoUrls[i],@"type":@"7"};
          [_submitArray addObject:dic1];
     }
     NSString *str = nil;
     //字符串
     NSMutableString *string = [[NSMutableString alloc] init];
     str = [string JSONString];
     str = [_submitArray JSONString];
     CYLog(@"str = %@",str);
     NSString *datastr = [NSString stringWithString:str];
     CYLog(@"datastr = %@",datastr);
     [MBProgressHUD showMessage:nil toView:self.view];
     [CYHttpTool postWithURL:[CYURL shared].addGeneralInfoPic params:@{@"userId":userId,@"token":token,@"data":datastr}  success:^(id json) {
          [MBProgressHUD hideHUDForView:self.view];
          CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
          if (jsonInfo.isSuccess) {
               [MBProgressHUD showSuccess:jsonInfo.message];
               [self.navigationController popViewControllerAnimated:YES];
          }else{
               [MBProgressHUD showError:jsonInfo.message];
          }
     } failure:^(NSError *error) {
          [MBProgressHUD hideHUDForView:self.view];
          CYAlertView(@"网络错误");
     }];

     
}

- (IBAction)weixinClick:(id)sender {
 
     [MBProgressHUD showMessage:@"获取中..." toView:self.view];
     [CYHttpTool postWithURL:[CYURL shared].getWeiXin params:@{} success:^(id json) {
          [MBProgressHUD hideHUDForView:self.view];
          CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
          if (jsoninfo.isSuccess) {
               [MBProgressHUD hideHUDForView:self.view];
               NSDictionary *dic = jsoninfo.data;
               _weixinname = [dic objectForKey:@"weixin"];
               _imageUrl = [dic objectForKey:@"weixinerweima"];
               if (_weixinname&&_imageUrl) {
                    [self setupweixinView];
               }
          }
          
     } failure:^(NSError *error) {
          [MBProgressHUD hideHUDForView:self.view];
     }];
     
}
-(void)setupweixinView{
     UIView *bgView = [[UIView alloc] initWithFrame:self.view.frame];
     bgView.backgroundColor = [UIColor grayColor];
     bgView.alpha = 0.8;
     self.weixinbg = bgView;
     self.weixinbg.hidden = NO;
     [[UIApplication sharedApplication].keyWindow addSubview:_weixinbg];
     //     _shituview =[[UIView alloc]initWithFrame: CGRectMake(30,120,self.view.frame.size.width-60,400)];
     _weixinView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.size.width-100, 400)];
     _weixinView.center = self.view.center;
     _weixinView.backgroundColor = [UIColor whiteColor];
     [[UIApplication sharedApplication].keyWindow addSubview:_weixinView];
     [[UIApplication sharedApplication].keyWindow bringSubviewToFront:_weixinView];
     
     UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
     button.frame = CGRectMake(10, 10, 20, 20);
     [button setImage:[UIImage imageNamed:@"icon_close_theme"] forState:UIControlStateNormal];
     
     [button addTarget:self action:@selector(viewbeclose) forControlEvents:UIControlEventTouchUpInside];
     [_weixinView addSubview:button];
     
     UILabel *noticelab = [[UILabel alloc]init];
     noticelab.frame = CGRectMake(0, button.y+button.height+20, _weixinView.width, 30);
     noticelab.text = @"请添加审核微信号";
     noticelab.textAlignment = NSTextAlignmentCenter;
     noticelab.font = [UIFont systemFontOfSize:14.0];
     [_weixinView addSubview:noticelab];
     
     UILabel *weixinLab = [[UILabel alloc]init];
     weixinLab.frame = CGRectMake(60, noticelab.height+noticelab.y+20, _weixinView.width/2-50, 30);
     weixinLab.textAlignment = NSTextAlignmentCenter;
     weixinLab.backgroundColor = CYColor(196, 196, 196, 1);
     weixinLab.layer.borderWidth = 1.0f;
     weixinLab.layer.borderColor = [UIColor lightGrayColor].CGColor;
     weixinLab.text = _weixinname;
     
     UIButton *copybtn = [[UIButton alloc]init];
     [copybtn setTitle:@"复制" forState:UIControlStateNormal];
     copybtn.frame = CGRectMake(weixinLab.x+weixinLab.width,weixinLab.y , _weixinView.width-120-weixinLab.width, 30);
     [copybtn addTarget:self action:@selector(copyclick) forControlEvents:UIControlEventTouchUpInside];
     copybtn.backgroundColor = CYColor(112, 181, 91, 1);
     [_weixinView addSubview:weixinLab];
     [_weixinView addSubview:copybtn];
     
     UILabel *erweimaLab = [[UILabel alloc]init];
     erweimaLab.frame = CGRectMake(0, weixinLab.height+weixinLab.y+20, _weixinView.width, 20);
     erweimaLab.text = @"审核微信二维码";
     erweimaLab.font = [UIFont systemFontOfSize:14];
     erweimaLab.textAlignment = NSTextAlignmentCenter;
     [_weixinView addSubview:erweimaLab];
     
     UIImageView *iamgeview = [[UIImageView alloc]initWithFrame:CGRectMake(_weixinView.width/4, erweimaLab.y+erweimaLab.height+20, _weixinView.width/2, _weixinView.width/2)];
     [iamgeview sd_setImageWithURL:[NSURL URLWithString:_imageUrl]];
     //    iamgeview.backgroundColor = [UIColor grayColor];
     
     [_weixinView addSubview:iamgeview];
     
     UILabel *lastnoticeLab = [[UILabel alloc]initWithFrame:CGRectMake(0, iamgeview.height+iamgeview.y+10, _weixinView.width, 20)];
     lastnoticeLab.textAlignment = NSTextAlignmentCenter;
     lastnoticeLab.text = @"扫描微信";
     lastnoticeLab.font = [UIFont systemFontOfSize:14];
     [_weixinView addSubview:lastnoticeLab];
     
}

-(void)copyclick{
     UIPasteboard *pab = [UIPasteboard generalPasteboard];
     [pab setString:_weixinname];
     if (pab == nil) {
          [MBProgressHUD showError:@"复制失败"];
          
     }else
     {
          [MBProgressHUD showSuccess:@"已复制"];
          
     }
}


-(void)viewbeclose{
     _weixinbg.hidden = YES;
     _weixinView.hidden = YES;
     
}



- (void)setimagecerIDView{
     // image 前缀
     NSString *preFixString = @"http://image.credit-manage.com/";
     // 屏幕的宽度 (也是承载imageView的view的宽度)
     CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width;
     // image各个边界的间隔
     CGFloat space = 10.f;
     // imageview的width (设定为5张)
     CGFloat imgWidth = (screenWidth - space * 6 ) / 5;
     // imageview的height
     CGFloat imgHeight = _recordView.frame.size.height - space * 2;
     // 由于是xib + 手码, 代码获取xib控件的frame 必须在主线程中获取
     dispatch_async(dispatch_get_main_queue(), ^{
          CYUser *user = [CYLoginHttpTool userData].user;
          [CYHttpTool postWithURL:[CYURL shared].getGeneralInfoPics params:@{@"userId":user.userId,@"token":user.token} success:^(id json) {
               //        CYLog(@"json = %@",json);
               CYJsonInfo *jsoninf = [CYJsonInfo objectWithKeyValues:json];
               NSMutableArray *data = jsoninf.data;
               for (NSDictionary *dic in data) {
                    // 取网络	图片地址
                    NSString *provePicAddress = [dic objectForKey:@"generalPicAddress"];
                    [_shenghuorecordArray addObject:provePicAddress];
                    for (int i = 0; i < _shenghuorecordArray.count; i++ ) {
                         // image的url string
                         NSString *imgUrlString = [_shenghuorecordArray objectAtIndex:i];
                         imgUrlString = [preFixString stringByAppendingString:imgUrlString];
                         // 创建imageView
                         UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(space + (imgWidth + space) * i, space, imgWidth, imgHeight)];
                         imgView.backgroundColor = [UIColor whiteColor];
                         // 此处你可使用SDWebImage来加载
                         [imgView sd_setImageWithURL:[NSURL URLWithString:imgUrlString]];
                         [_recordView addSubview:imgView];
                    }
                    if (_shenghuorecordArray.count){
                         _recordLab.hidden = YES;
                         UITapGestureRecognizer *tag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoBrowser:)];
                         [_recordView addGestureRecognizer:tag];
                    }
               }
               
          } failure:^(NSError *error) {
               
          }];
     });
     
}

- (IBAction)shiyitu1Click:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/prove/shenghuozhao1.jpg"]];
     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];
}

- (IBAction)shiyitu2Click:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/prove/shenghuozhao2.jpg"]];
     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];
}

/**
 *  图片浏览器
 */
- (void)photoBrowser:(UITapGestureRecognizer *)tag {
     NSArray *urls = _shenghuorecordArray;
     MWPhoto *photo = nil;
     NSMutableArray *photos = [NSMutableArray array];
     for (NSString *url in urls) {
          photo = [MWPhoto photoWithURL:CYURLWithService(url)];
          //        photo.caption = @"title";
          [photos addObject:photo];
     }
     [LEPhotoBrowserTool showPhotoBrowserWithController:self photos:photos];
}

- (void)setupUploadView {
     //生活照
     [LEUnitView imageScrollView:self.submitView controller:self block:^(LEUnitView *unitView, LEUnitCell *cell, UIImage *image) {
          [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
               [_photoUrls addObject:imageUrl];
               cell.ratio = 1;
          } failure:^(NSError *error) {
               //删除
               [unitView deleteLastCell];
          } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
               CGFloat a = totalBytesWritten;
               CGFloat b = totalBytesExpectedToWrite;
               cell.ratio = a/b - .01;
          }];
     } cellClick:^(LEUnitView *unitView, LEUnitCell *cell) {
     }];
}


- (void)loaddetails{

          CYUser *user = [CYLoginHttpTool userData].user;
          //必填类状态:
          NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];//获取version
        [MBProgressHUD showMessage:@"加载中..." toView:self.view];

          NSString *versionstr = [NSString stringWithFormat:@"ios%@",appVersion];
          [CYHttpTool postWithURL:[CYURL shared].getGeneralInfoStatus params:@{@"userId":user.userId,@"token":user.token,@"version":versionstr} success:^(id json) {
               [MBProgressHUD hideHUDForView:self.view];
               CYJsonInfo *genealjsonInfo = [CYJsonInfo objectWithKeyValues:json];
               if (genealjsonInfo.isSuccess) {
                    [MBProgressHUD hideHUDForView:self.view];
                    NSMutableDictionary *data = genealjsonInfo.data;
                    _weiXin = [data objectForKey:@"weiXin"];
                    _weixinLab.text = [NSString stringWithFormat:@"%@",_weiXin];
                    _qq = [data objectForKey:@"qq"];
                    _qqLab.text = [NSString stringWithFormat:@"%@",_qq];
                    NSMutableDictionary *picData = genealjsonInfo.data;
                    NSMutableArray *cerdidPic = [picData objectForKey:@"generalInfoPics"];
                    for (NSMutableDictionary *picdic in cerdidPic) {
                         NSString *str = [picdic objectForKey:@"generalPicAddress"];
                         [_creditarray addObject:str];
                    }
                    
                    NSMutableArray *cerdiphone = [picData objectForKey:@"lphones"];
                    for (NSMutableDictionary *phonedic in cerdiphone) {
                         NSString *phones = [phonedic objectForKey:@"phone"];
                         [_lphonesarray addObject:phones];
                         NSString *name = [phonedic objectForKey:@"name"];
                         [_namearray addObject:name];
                    }
                    if (_lphonesarray.count) {
                         _addresspersonLab.text = [NSString stringWithFormat:@"%@ %@",_namearray[0],_lphonesarray[0]];
                         
                    }else{
                         _addresspersonLab.text = @" -- ";
                    }
                 }
               
               } failure:^(NSError *error) {
               CYLog(@"error =%@",error);
               [MBProgressHUD hideHUDForView:self.view];
               
          }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
